package com.soecode.lyf.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.soecode.lyf.dao.DeptDao;
import com.soecode.lyf.dao.PersonRecordDao;
import com.soecode.lyf.entity.Dept;
import com.soecode.lyf.entity.PersonRecord;
import com.soecode.lyf.service.PersonRecordService;

@Service
public class PersonRecordServiceImpl implements PersonRecordService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	// 注入Service依赖
	@Autowired
	private PersonRecordDao personRecordDao;
	@Autowired
	private DeptDao deptDao;

	@Override
	public List<PersonRecord> queryPersonRecord(String name, String dept, String beginDate, String endDate) {
		List<String> deptIdList = Lists.newArrayList();
		if (dept != null && dept != "") {
			deptIdList.add(dept);
			List<Dept> deptList = deptDao.queryDeptByParentID(dept);
			queryDeptByParentId(deptList, deptIdList);
		}
		return personRecordDao.queryPersonRecord(name, deptIdList, beginDate, endDate);
	}

	@Override
	public List<PersonRecord> queryPersonRecordOrderByNo(String name, String dept, String beginDate, String endDate) {
		List<String> deptIdList = Lists.newArrayList();
		if (dept != null && dept != "") {
			deptIdList.add(dept);
			List<Dept> deptList = deptDao.queryDeptByParentID(dept);
			queryDeptByParentId(deptList, deptIdList);
		}
		return personRecordDao.queryPersonRecordOrderByNo(name, deptIdList, beginDate, endDate);
	}

	// 迭代查询公司组织架构，要求数据库不允许循环依赖
	private void queryDeptByParentId(List<Dept> deptList, List<String> deptIdList) {
		if (deptList != null && !deptList.isEmpty()) {
			for (Dept d : deptList) {
				deptIdList.add(d.getId());
				List<Dept> newDeptList = deptDao.queryDeptByParentID(d.getId());
				queryDeptByParentId(newDeptList, deptIdList);
			}
		}
	}
}
